<template>
    <div>
        <van-popup
                class="wdp-1 fullWin"
                v-model="visible"
                :closeable="false"
                close-icon="close"
                position="right"
        >
            <!--导航栏-->
            <bpm-nav-bar :title="navBarTitle" :leftArrow="true" @close="close"></bpm-nav-bar>

            <!--业务表单-->
            <component ref="form" :is="componentFile" :bpmIdType="bpmIdType" :formId="formId" :formCode="formCode"
                       :editableList="editableList" :startPage="startPage"/>

            <bpm-hist-list v-if="!startPage" :flow-comment-list="flowCommentList"></bpm-hist-list>
            <user-group v-else :actorUserList="actorUserList" :actorDeptList="actorDeptList" v-model="userList"
                        :isRadio="isRadio"></user-group>

            <van-grid :column-num="columnNum" class="py-5">
                <van-grid-item v-if="buttonVoList.save">
                    <van-button type="default" size="large" @click="save">保存草稿</van-button>
                </van-grid-item>
                <van-grid-item v-if="buttonVoList.start || buttonVoList.submit || buttonVoList.finishPassRound">
                    <van-button type="primary" size="large" @click="start" v-if="buttonVoList.start">立即提交</van-button>
                    <van-button type="primary" size="large" @click="submit" v-if="buttonVoList.submit">立即提交</van-button>
                    <van-button type="primary" size="large" @click="finishPassRound"
                                v-if="buttonVoList.finishPassRound">
                        填写意见
                    </van-button>
                </van-grid-item>
                <van-grid-item v-if="buttonVoList.rejectFirstTask || buttonVoList.reBack">
                    <van-button type="warning" size="large" @click="rejectFirstTask"
                                v-if="buttonVoList.rejectFirstTask">
                        驳回
                    </van-button>
                    <van-button type="warning" size="large" @click="reBack" v-if="buttonVoList.reBack">收回</van-button>
                </van-grid-item>
                <van-grid-item v-if="
                    buttonVoList.addUser ||
                    buttonVoList.addPassRound ||
                    buttonVoList.transferTask ||
                    buttonVoList.delegateTask ||
                    buttonVoList.rejectPreTask ||
                    buttonVoList.reBackFirst
                    ">
                    <van-button
                            type="info"
                            size="large"
                            @click="moreButtonShow = true">
                        更多操作
                    </van-button>
                </van-grid-item>
            </van-grid>
        </van-popup>

        <van-action-sheet v-model="moreButtonShow" :actions="moreActions" @select="onSelect"/>

        <flowIdeaPopup ref="bpmSelectUserDialog" @selectUserBack="selectUserBack"></flowIdeaPopup>
    </div>
</template>

<script>

    import bpmNavBar from '../../components/bpmNavBar';
    import flowIdeaPopup from './bpmButton/flowIdeaPopup'
    import bpmHistList from './bpmButton/bpmHistList';
    import userGroup from "./bpmButton/userGroup";

    //TODO 浮层内嵌浮层
    export default {
        name: 'flowApprove',
        components: {
            bpmNavBar,
            flowIdeaPopup,
            bpmHistList,
            userGroup,
        },
        data() {
            return {
                visible: false,
                componentFile: null,
                componentUrl: null,
                buttonDatas: {},
                bpmId: null,
                bpmIdType: null,
                formCode: null,
                processInstanceId: null,
                processDefId: null,
                formId: null,
                editableList: [],
                startPage: false,//是否启动页面
                buttonVoList: {},
                moreButtonShow: false,
                actorUserList: [],
                actorDeptList: [],
                userList: [],
                isRadio: false,
                transitionId: null,
                url: {
                    getProcessDefListByFormCode: '/api/bpm/bpm-front/displayRest/getProcessDefListByFormCode/v1',
                    getActorsOfSecondNode: "/api/bpm/bpm-front/mobileRest/getActorsOfSecondNode/v1",
                    getBpmOperateVo: "/api/bpm/bpm-front/displayRest/getBpmOperateVo/v1",
                    getIdeaListByInstanceId: "/api/bpm/bpm-front/mobileRest/getIdeaListByInstanceId/v1",
                    getDealData: "/api/bpm/bpm-front/displayRest/getDealData/v1",
                    autoSubmitToSecondNode: "/api/bpm/bpm-front/mobileRest/autoSubmitToSecondNode/v1",
                    submit: "/api/bpm/bpm-front/operateRest/submit/v1",
                    addUser: "/api/bpm/bpm-front/operateRest/addUser/v1",
                    addUserAndSubmit: "/api/bpm/bpm-front/operateRest/addUserAndSubmit/v1",
                    removeUser: "/api/bpm/bpm-front/operateRest/removeUser/v1",
                    addPassRound: "/api/bpm/bpm-front/operateRest/addPassRound/v1",
                    addPassRoundAndSubmit: "/api/bpm/bpm-front/operateRest/addPassRoundAndSubmit/v1",
                    removePassRound: "/api/bpm/bpm-front/operateRest/removePassRound/v1",
                    delegateTask: "/api/bpm/bpm-front/operateRest/delegateTask/v1",
                    jump: "/api/bpm/bpm-front/operateRest/jump/v1",
                    rejectPreTask: "/api/bpm/bpm-front/operateRest/rejectPreTask/v1",
                    rejectFirstTask: "/api/bpm/bpm-front/operateRest/rejectFirstTask/v1",
                    rejectWantTask: "/api/bpm/bpm-front/operateRest/rejectWantTask/v1",
                    finishPassRound: "/api/bpm/bpm-front/operateRest/finishPassRound/v1",
                    reBack: "/api/bpm/bpm-front/operateRest/reBack/v1",
                    reBackFirst: "/api/bpm/bpm-front/operateRest/reBackFirst/v1",
                    reDelegateTask: "/api/bpm/bpm-front/operateRest/reDelegateTask/v1",
                    transferTask: "/api/bpm/bpm-front/operateRest/transferTask/v1",
                    pressTodo: "/api/bpm/bpm-front/operateRest/pressTodo/v1",
                    suspend: "/api/bpm/bpm-front/operateRest/suspend/v1",
                    activate: "/api/bpm/bpm-front/operateRest/activate/v1",
                },
                currentUrl: null,
                flowCommentList: [],
                navBarTitle: '',
                gotoIndexFlg: false,
            }
        },
        computed: {
            columnNum() {
                let result = 0;
                if (this.buttonVoList.save) {
                    result++;
                }
                if (this.buttonVoList.start || this.buttonVoList.submit || this.buttonVoList.finishPassRound) {
                    result++;
                }
                if (this.buttonVoList.rejectFirstTask || this.buttonVoList.reBack) {
                    result++;
                }
                if (this.buttonVoList.addUser ||
                    this.buttonVoList.addPassRound ||
                    this.buttonVoList.transferTask ||
                    this.buttonVoList.delegateTask ||
                    this.buttonVoList.rejectPreTask ||
                    this.buttonVoList.reBackFirst) {
                    result++;
                }
                return result > 1 ? result : 2;
            },
            moreActions() {
                const actions = [];
                if (this.buttonVoList.addUser) {
                    actions.push({
                        id: 'addUser',
                        name: '加签'
                    });
                }
                if (this.buttonVoList.addPassRound) {
                    actions.push({
                        id: 'addPassRound',
                        name: '传阅'
                    });
                }
                if (this.buttonVoList.transferTask) {
                    actions.push({
                        id: 'transferTask',
                        name: '转办'
                    });
                }
                if (this.buttonVoList.delegateTask) {
                    actions.push({
                        id: 'delegateTask',
                        name: '委托'
                    });
                }
                if (this.buttonVoList.rejectPreTask) {
                    actions.push({
                        id: 'rejectPreTask',
                        name: '退回上一步'
                    });
                }
                if (this.buttonVoList.reBackFirst) {
                    actions.push({
                        id: 'reBackFirst',
                        name: '撤销'
                    });
                }
                return actions;
            }
        },
        methods: {
            close() {
                this.visible = false;
                //还原数据
                this.componentFile = null;
                this.componentUrl = null;
                this.buttonDatas = {};
                this.bpmId = null;
                this.bpmIdType = null;
                this.formCode = null;
                this.processInstanceId = null;
                this.processDefId = null;
                this.formId = null;
                this.editableList = [];
                this.startPage = false;
                this.buttonVoList = {};
                this.moreButtonShow = false;
                this.actorUserList = [];
                this.actorDeptList = [];
                this.userList = [];
                this.isRadio = false;
                this.transitionId = null;
                this.flowCommentList = [];
                this.navBarTitle = '';
            },
            addFromProcess(processDefId) {
                this.bpmId = processDefId;
                this.bpmIdType = "processDefId";
                this.refresh(true);
                this.visible = true;
            },
            detailFromTask(taskId) {
                this.bpmId = taskId;
                this.bpmIdType = "taskId";
                this.refresh(true);
                this.visible = true;
            },
            detailFromBusiness(formId, formCode) {
                this.bpmId = formId;
                this.bpmIdType = "formId";
                this.formCode = formCode;
                this.refresh(true);
                this.visible = true;
            },
            initActorArray(processDefId) {
                this.$mask.open();
                this.$http.get(this.url.getActorsOfSecondNode, {
                    params: {
                        processDefId: processDefId
                    }
                }).then((res) => {
                    if (res.success) {
                        this.actorUserList = res.result.users || [];
                        this.actorDeptList = res.result.depts || [];
                        this.isRadio = res.result.radio;
                        this.transitionId = res.result.transitionId;
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            refresh(init) {
                const that = this;
                this.$mask.open();
                this.$http.get(this.url.getBpmOperateVo, {
                    params: {
                        id: this.bpmId,
                        idType: this.bpmIdType,
                        formCode: this.formCode,
                    }
                }).then((res) => {
                    that.init(res, init);
                }).catch(() => {
                    this.close();
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            init(res, init) {
                if (res.success) {
                    this.buttonDatas = res.result;
                    if (this.buttonDatas.open) {
                        this.componentUrl = this.buttonDatas.mobileUrl;
                        this.bpmId = this.buttonDatas.bpmId;
                        this.bpmIdType = this.buttonDatas.bpmIdType;
                        this.formCode = this.buttonDatas.formCode;
                        this.processInstanceId = this.buttonDatas.processInstanceId;
                        this.processDefId = this.buttonDatas.processDefId;
                        this.formId = this.buttonDatas.formId;
                        this.startPage = !this.processInstanceId;
                        this.editableList = this.buttonDatas.editableList || [];
                        const buttonVoList = this.buttonDatas.buttonVoList;
                        this.buttonVoList = {};
                        buttonVoList.forEach(vo => {
                            this.buttonVoList[vo.type] = vo;
                        });
                        if (this.buttonDatas.title) {
                            this.navBarTitle = this.buttonDatas.title;
                        } else if (this.processInstanceId) {
                            this.navBarTitle = '审批流程';
                        } else {
                            this.navBarTitle = '发起流程';
                        }
                        if (init) {
                            this.render();
                        }
                        if (this.startPage) {
                            if (init) {
                                if (this.processDefId) {
                                    this.initActorArray(this.processDefId);
                                } else if (this.formCode) {
                                    this.initProcessDefByFormCode();
                                } else {
                                    this.close();
                                    this.$notify({type: 'warning', message: '数据错误！'});
                                }
                            }
                        } else {
                            this.refreshFlowCommentList();
                        }
                    } else {
                        this.close();
                        this.$notify({type: 'warning', message: '没有权限！'});
                    }
                } else {
                    this.close();
                    this.$notify({type: 'warning', message: res.message});
                }
            },
            initProcessDefByFormCode() {
                this.$mask.open();
                this.$http.get(this.url.getProcessDefListByFormCode, {
                    params: {formCode: this.formCode}
                }).then((res) => {
                    if (res.success) {
                        if (res.result.length == 0) {
                            this.close();
                            this.$notify({
                                type: 'warning',
                                message: '没有找到formCode【' + this.formCode + '】对应的流程模板',
                                duration: 2000,
                            });
                        } else {
                            if (res.result.length > 1) {
                                this.$notify({
                                    type: 'warning',
                                    message: 'formCode【' + this.formCode + '】对应多个流程模板，默认选择一个',
                                    duration: 2000,
                                });
                            }
                            this.processDefId = res.result[0].id;
                            this.initActorArray(this.processDefId);
                        }
                    } else {
                        this.close();
                        this.$notify({type: 'warning', message: res.message, duration: 2000,});
                    }
                }).catch((err) => {
                    this.close();
                    this.$notify({type: 'warning', message: '请求失败: ' + err, duration: 2000,});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            render() {
                this.componentFile = () => ({
                    component: import(`@/view/` + this.componentUrl + ".vue"),
                    delay: 200,
                    timeout: 10000
                });
            },
            refreshFlowCommentList() {
                if (!this.processInstanceId) {
                    return;
                }
                this.$mask.open();
                this.$http.get(this.url.getIdeaListByInstanceId, {params: {processInstanceId: this.processInstanceId}}).then((res) => {
                    this.flowCommentList = res.result;
                }).catch(() => {
                }).finally(() => {
                    this.$mask.close();
                });
            },
            /**以下是流程动作**/
            save() {
                this.$refs.form.save();
                this.gotoIndexFlg = false;
            },
            /*启动*/
            start() {
                if (this.userList.length == 0) {
                    this.$notify({type: 'warning', message: "请选接收人"});
                    return;
                }
                this.$refs.form.save(this.startBack, this.buttonVoList.start.attribute.processDefId || this.processDefId);
            },
            startBack(formId) {
                this.gotoIndexFlg = false;
                this.bpmId = formId;
                this.bpmIdType = "formId";

                const userListMap = {};
                userListMap[this.transitionId] = this.userList.map(item => item.userKey);
                const returnData = {
                    userListMap: userListMap
                };
                this.$mask.open();
                this.$http.put(this.url.autoSubmitToSecondNode + "?formId=" + formId, returnData).then((res) => {
                    if (res.success) {
                        this.$notify({type: 'success', message: res.message});
                        this.close();
                        this.$emit("refresh");
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                        this.refresh(false);
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: "操作失败，请重试"});
                    this.refresh(false);
                }).finally(() => {
                    this.$mask.close();
                });
            },
            submit() {
                this.$mask.open();
                this.$http.get(this.url.getDealData, {params: {taskId: this.buttonVoList.submit.attribute.taskId}}).then((res) => {
                    if (res.success) {
                        if (res.result.last) {
                            if (res.result.transitionList.length == 0) {
                                this.$notify({type: 'warning', message: '没有流转目标'});
                            } else {
                                this.doSubmit(res.result.transitionList[0]);
                            }
                        } else {
                            this.doSubmit();
                        }
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
            doSubmit(transition) {
                this.currentUrl = this.url.submit + "?taskId=" + this.buttonVoList.submit.attribute.taskId;
                if (transition) {
                    this.$refs.bpmSelectUserDialog.openForSubmit(this.buttonVoList.submit, transition);
                } else {
                    this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.submit);
                }
                this.gotoIndexFlg = true;
            },
            /*退回申请人*/
            rejectFirstTask() {
                this.currentUrl = this.url.rejectFirstTask + "?taskId=" + this.buttonVoList.rejectFirstTask.attribute.taskId;
                this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.rejectFirstTask);
                this.gotoIndexFlg = true;
            },
            /*填写传阅意见*/
            finishPassRound() {
                this.currentUrl = this.url.finishPassRound + "?taskId=" + this.buttonVoList.finishPassRound.attribute.taskId;
                this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.finishPassRound);
                this.gotoIndexFlg = true;
            },
            /*收回*/
            reBack() {
                this.currentUrl = this.url.reBack + "?taskId=" + this.buttonVoList.reBack.attribute.taskId;
                this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.reBack);
                this.gotoIndexFlg = true;
            },
            onSelect(item) {
                this.moreButtonShow = false;
                this.callFn(this.buttonVoList[item.id])
            },
            /*流程操作按钮动态调用*/
            callFn(button) {
                this[button.type].apply(this);
            },
            /*加签*/
            addUser() {
                this.currentUrl = this.url.addUser + "?taskId=" + this.buttonVoList.addUser.attribute.taskId;
                this.$refs.bpmSelectUserDialog.open(this.buttonVoList.addUser);
                this.gotoIndexFlg = false;
            },
            /*增加传阅人*/
            addPassRound() {
                this.currentUrl = this.url.addPassRound + "?taskId=" + this.buttonVoList.addPassRound.attribute.taskId;
                this.$refs.bpmSelectUserDialog.open(this.buttonVoList.addPassRound);
                this.gotoIndexFlg = false;
            },
            /*转办*/
            transferTask() {
                this.currentUrl = this.url.transferTask + "?taskId=" + this.buttonVoList.transferTask.attribute.taskId;
                this.$refs.bpmSelectUserDialog.open(this.buttonVoList.transferTask);
                this.gotoIndexFlg = true;
            },
            /*委托*/
            delegateTask() {
                this.currentUrl = this.url.delegateTask + "?taskId=" + this.buttonVoList.delegateTask.attribute.taskId;
                this.$refs.bpmSelectUserDialog.open(this.buttonVoList.delegateTask);
                this.gotoIndexFlg = true;
            },
            /*退回上一步*/
            rejectPreTask() {
                this.currentUrl = this.url.rejectPreTask + "?taskId=" + this.buttonVoList.rejectPreTask.attribute.taskId;
                this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.rejectPreTask);
                this.gotoIndexFlg = true;
            },
            /*撤销*/
            reBackFirst() {
                this.currentUrl = this.url.reBackFirst + "?taskId=" + this.buttonVoList.reBackFirst.attribute.taskId;
                this.$refs.bpmSelectUserDialog.openNoUser(this.buttonVoList.reBackFirst);
                this.gotoIndexFlg = true;
            },
            selectUserBack(data) {
                this.$mask.open();
                this.$http.put(this.currentUrl, data).then((res) => {
                    if (res.success) {
                        if (this.gotoIndexFlg) {
                            this.$notify({type: 'success', message: res.message});
                            this.close();
                        } else {
                            this.$notify({type: 'success', message: res.message});
                            this.refresh(false);
                        }
                        this.$emit("refresh");
                    } else {
                        this.$notify({type: 'warning', message: res.message});
                    }
                }).catch(() => {
                    this.$notify({type: 'warning', message: '请求发生错误'});
                }).finally(() => {
                    this.$mask.close();
                });
            },
        }
    }
</script>
